package com.example.chapter04;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.chapter04.util.DateUtil;

public class ActRequestActivity extends AppCompatActivity implements View.OnClickListener {

    private final String mRequest = "你好，在吗？";
    private ActivityResultLauncher<Intent> activityResultLauncher;
    private TextView tv_request;
    private TextView tv_get_response;
    private Button btn_request;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_request);
        tv_request = findViewById(R.id.tv_request);
        tv_request.setText(mRequest);
        tv_get_response = findViewById(R.id.tv_get_response);

        btn_request = findViewById(R.id.btn_request);
        btn_request.setOnClickListener(this);

        activityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result != null) {
                            Intent intent = result.getData();
                            if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                                Bundle bundle = intent.getExtras();
                                String back_response_time = bundle.getString("response_time");
                                String back_response_content = bundle.getString("response_content");
                                String desc = String.format("返回时间：%s\n返回消息：%s", back_response_time, back_response_content);
                                tv_get_response.setText(desc);
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, ActResponseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("request_content", mRequest);
        bundle.putString("request_time", DateUtil.getNowDateTime());
        intent.putExtras(bundle);
        // startActivityForResult(, );  弃用
        activityResultLauncher.launch(intent);
    }

}